package com.qianyucc.blog.controller.admin;

import cn.hutool.core.util.*;
import com.qianyucc.blog.model.dto.*;
import com.qianyucc.blog.model.pojo.*;
import com.qianyucc.blog.model.vo.*;
import com.qianyucc.blog.service.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/**
 * @author lijing
 * @e-mail 1413979079@qq.com
 * @date 2020-03-21 11:08
 * @description
 */
@Slf4j
@RestController("adminBlogController")
@RequestMapping("/admin/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private ConfigService configService;

    @ApiOperation("导出博客数据")
    @GetMapping("/export")
    public void export(HttpServletResponse res, String token) {
        boolean isValid = configService.checkToken(token);
        if (!isValid) {
            res.setStatus(HttpStatus.FORBIDDEN.value());
            return;
        }
        res.setContentType("application/forc-download");
        res.setHeader("Content-Disposition", "attachment;filename=blog_data.db");
        BlogData blogData = blogService.export();
        ServletOutputStream out = null;
        try {
            out = res.getOutputStream();
            byte[] bytes = ObjectUtil.serialize(blogData);
            out.write(bytes);
        } catch (IOException e) {
            log.error("导出博客数据中，文件下载失败:{}", e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation("导入博客数据")
    @PostMapping("/import")
    public ResultVO importData(@RequestParam("blogData") MultipartFile file) {
        try {
            ObjectInputStream ois = new ObjectInputStream(file.getInputStream());
            BlogData blogData = (BlogData) ois.readObject();
            blogService.importData(blogData);
        } catch (IOException e) {
            log.error("导入博客数据，文件上传失败:{}", e.getMessage());
            return ResultVO.error("数据导入失败");
        } catch (ClassNotFoundException e) {
            log.error("导入博客数据，{}", e.getMessage());
            return ResultVO.error("数据导入失败");
        }
        return ResultVO.ok("数据导入成功");
    }


    @ApiOperation("修改或插入博客信息")
    @PostMapping("/profile")
    public ResultVO updProfile(@RequestBody ProfileDTO profileDTO) {
        configService.updConfig(profileDTO);
        return ResultVO.ok("操作成功");
    }

    @ApiOperation("获取统计图表的信息")
    @GetMapping("/chart")
    public Map<String, Object> getArticlesCountByMouth() {
        return blogService.countByMonth();
    }
}
